<template>
  <div>
    <el-dialog
      :title="editData.id ? '编辑规则引擎' : '新增规则引擎'"
      :visible.sync="dialogVisible"
      width="1000px"
      :before-close="closeAddDialog"
      :close-on-click-modal="false"
    >
      <el-form
        :model="addForm"
        :rules="rules"
        ref="refAddForm"
        label-width="100px"
      >
        <el-form-item size="small" label="规则名称" prop="name">
          <el-input
            clearable
            v-model.trim="addForm.name"
            placeholder="请输入规则名称"
            maxlength="20"
            style="width: 100%"
          >
          </el-input>
        </el-form-item>
        <!-- <el-form-item size="small" label="规则类型">
                    <el-select v-model="addForm.type" filterable placeholder="请选择规则类型" style="width: 100%">
                        <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item> -->
        <el-form-item size="small" label="场景描述">
          <el-input
            placeholder="请输入场景描述"
            maxlength="30"
            rows="3"
            type="textarea"
            v-model="addForm.description"
            resize="none"
            :autosize="{ minRows: 2, maxRows: 5 }"
          ></el-input>
        </el-form-item>
        <el-tabs
          type="border-card"
          v-model="activeName"
          @tab-click="handleClick"
        >
          <el-tab-pane label="监听器" name="1">
            <listener
              ref="reflistener"
              @onlisteners="onlisteners"
              :listeners="addForm.listeners"
            />
          </el-tab-pane>
          <el-tab-pane label="过滤器" name="2">
            <filtera
              ref="reffiltera"
              @onfiltera="onfiltera"
              :filters="addForm.filters"
            />
          </el-tab-pane>
          <el-tab-pane label="输出" name="3">
            <Output
              ref="refOutput"
              @onactions="onactions"
              :list="addForm.actions"
              actions="device,http,alert"
            />
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeAddDialog" class="cancel-button"
          >取 消</el-button
        >
        <el-button
          size="small"
          class="confirm-button"
          @click="addSubmit"
          v-preventReClick="1000"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { reqRuleEdit } from "@api/rule";
import { mapState } from "vuex";
import loadMore from "@mixin/loadMore";
import Listener from "../modules/listener.vue";
import Filtera from "../modules/filtera.vue";
import Output from "../modules/output.vue";

export default {
  mixins: [loadMore],
  components: { Listener, Filtera, Output },
  props: {
    editData: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      dialogVisible: false,
      activeName: "1",
      addForm: {
        name: "",
        type: "scene",
        description: "",
        state: "",
        uid: "",
        // 监听器
        listeners: [
          // {
          //     type: "device",//类型：设备device
          //     pk: "openiitagateway02",//产品id
          //     config:"",//listeners值转字符串
          //     conditions:[
          //         {
          //             parameters:"",//参数集合
          //             identifier:"",//标识
          //             type:"",//标识类型
          //         }
          //     ]
          // }
        ],
        // 过滤器
        filters: [
          // {
          //     type: "device",//类型：设备device
          //     pk: "openiitagateway02",//产品id
          //     dn:"",
          //     config:"",
          //     deviceRadio:"指定设备",
          //     conditions:[
          //         {
          //             parameters:"",//参数集合
          //             type:"",//标识类型
          //             comparator:"",//算数符
          //             identifier:"",//标识
          //             value:"",//标识值
          //         }
          //     ]
          // }
        ],
        // 执行器
        actions: [
          // {
          //     type: "",//类型：设备控制device，推送http
          //     saved: true,
          //     config: "",
          //     services: [
          //         {
          //             device: "Rf4QSjbm65X45753/TEST_SW_000047",//产品 + / + 设备imei
          //             identifier: "set",//标识
          //             inputData: [
          //                 {
          //                     identifier: "powerstate",//输出表述
          //                     value: "off"//输出值
          //                 }
          //             ]
          //         }
          //     ],
          // }
        ],
      },
      typeList: [
        {
          id: "scene",
          name: "场景联动",
        },
        {
          id: "flow",
          name: "数据流转",
        },
      ],
      // 表单验证规则
      rules: {
        name: [
          {
            required: true,
            message: "请输入规则名称",
            trigger: "blur",
          },
        ],
        userId: [
          {
            required: true,
            message: "请选择规则类型",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  watch: {
    dialogVisible(e) {
      if (e) {
        if (this.editData.id) {
          console.log(this.editData, "编辑");
          // 编辑
          this.addForm = this.editData;
          this.addForm.filters = JSON.parse(this.addForm.filters);
          this.addForm.listeners = JSON.parse(this.addForm.listeners);
          this.addForm.actions = JSON.parse(this.addForm.actions);
          console.log(this.addForm.listeners, "编辑listeners");
        }
        this.$nextTick(() => {
          // 新增 ||编辑
          this.$refs.reflistener.getList();
        });
      }
    },
  },
  methods: {
    handleClick(tab, event) {
      // console.log(tab.paneName);
      if (tab.paneName == "3") {
        this.$nextTick(() => {
          this.$refs.refOutput.getList();
        });
      } else if (tab.paneName == "2") {
        this.$nextTick(() => {
          this.$refs.reffiltera.getList();
        });
      }
    },
    // 监听器赋值
    onlisteners(row) {
      this.addForm.listeners = row.map((item) => {
        return {
          ...item,
          config: JSON.stringify(item),
        };
      });
      console.log(this.addForm.listeners, "this.addForm.listeners");
    },
    // 过滤器赋值
    onfiltera(row) {
      this.addForm.filters = row.map((item) => {
        return {
          ...item,
          config: JSON.stringify(item),
        };
      });
      // console.log(this.addForm.filters,'this.addForm.filters');
    },
    // 输出赋值
    onactions(row) {
      this.addForm.actions = row;
      // this.addForm.actions = row.map(item => {
      //         item.saved = true
      //         if (item.config) {
      //             return item
      //         }
      //         return {
      //             ...item,
      //             config: JSON.stringify(item),
      //         }
      //     })
    },
    // 点击新增
    addSubmit() {
      this.$refs.refAddForm.validate(async (valid) => {
        if (!valid) return;
        // try {
        //     let ssss = await this.$refs.refOutput.validateForm2(); // 调用子页面的验证方法
        // } catch (error) {
        //     console.error(error);
        //     this.$modal.notifyWarning('告警名称不能为空');
        // }
        // return;
        delete this.addForm.createAt;
        this.addForm.actions = this.addForm.actions.map((item) => {
          item.saved = true;
          if (item.config) {
            return item;
          }
          return {
            ...item,
            config: JSON.stringify(item),
          };
        });
        const res = await reqRuleEdit({
          ...this.addForm,
          tenantId: this.user.tenantId,
        });
        if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
        this.$modal.notifySuccess("新增成功");
        this.closeAddDialog();
        this.$parent.getDataList();
      });
    },
    // 点击关闭弹框
    closeAddDialog() {
      this.$refs.refAddForm.resetFields();
      this.dialogVisible = false;
      this.addForm = {
        name: "",
        type: "scene",
        description: "",
        state: "",
        uid: "",
        // 监听器
        listeners: [],
        // 过滤器
        filters: [],
        // 执行器
        actions: [],
      };
      this.activeName = "1";
      this.$refs.reflistener.getDestroy();
      this.$refs.reffiltera.getDestroy();
      this.$refs.refOutput.getDestroy();
    },
  },
  mounted() {},
};
</script>

<style lang="less" scoped>
@import url("../../common.less");

::v-deep .el-tabs--border-card > .el-tabs__header .el-tabs__item.is-active {
  color: #7367f0;
}

::v-deep .el-tabs__header .el-tabs__item.is-active {
  border-bottom: 1px solid #7367f0;
}

/* 修改鼠标移入时的样式 */
::v-deep .el-tabs__item:hover {
  color: #7367f0 !important;
}
</style>
